package com.testing.class13;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.testing.common.AutoTools;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @Classname UploadTest
 * @Description 类型说明
 * @Date 2022/11/2 21:02
 * @Created by 特斯汀Roy
 */
public class UploadTest {
    public static CloseableHttpClient client= HttpClients.createDefault();

    public static void main(String[] args) throws IOException {
        uploadFile("http://www.testingedu.com.cn:8000/index.php/home/Uploadify/imageUp/savepath/head_pic/pictitle/banner/dir/images.html","{\"text\":{\"id\":\"WU_FILE_0\",\"NAME\":\"悠米微信 .png\"},\"file\":{\"file\":\"E:\\\\QSwork\\\\素材\\\\悠米微信 .png\"}}");
    }

    /***
     * 文件部分：{"file":"E:\png"}
     * 文本部分：{"id":"WU",“NAME”:"PNG"}
     * 构成整体参数;
     * {"text":{"id":"WU_FILE_0","NAME":"悠米微信 .png"},"file":{"file":"E:\\QSwork\\素材\\悠米微信 .png"}}
     */

    public static void uploadFile(String url,String param) throws IOException {
        //url和方法
        HttpPost upload=new HttpPost(url);
        //请求体，请求头
        //创建multipart实体的构造器
        MultipartEntityBuilder meb=MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);

        JSONObject allParams = JSON.parseObject(param);

        JSONObject fileParams = allParams.getJSONObject("file");
        for (String key : fileParams.keySet()) {
            meb.addBinaryBody(key,new File(fileParams.getString(key)));
        }

        JSONObject textParams = allParams.getJSONObject("text");
        //将其中的每个键值对都添加为textbody
        for (String key : textParams.keySet()) {
            meb.addTextBody(key,textParams.getString(key), ContentType.create("text/plain", Charset.forName("utf-8")));
        }

        HttpEntity fileEntity = meb.build();
        //会自动生成 content-type,并且发包的时候用的是自动生成的boundry。
        System.out.println("自己打出来的content-type是："+fileEntity.getContentType());
        upload.setEntity(fileEntity);
        //如果再去设置一次，反而会导致服务器无法识别。
//        upload.setHeader("Content-Type","multipart/form-data; boundary=----WebKitFormBoundaryBt5AGM7pcCJZ7JHG");

        String s = EntityUtils.toString(client.execute(upload).getEntity(), "utf-8");
        AutoTools.log.info(s);
    }
}
